import React, {
  useState,
  useEffect,
  useCallback,
  useMemo,
  useRef,
} from 'react';
import {
  Alert,
  Form,
  Select,
  InputNumber,
  Button,
  Row,
  Col,
  Table,
  Tag,
  Progress,
  message,
  Modal,
} from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import KeyStrategyDisplay from '@/components/KeyStrategyDisplay'



const { Option } = Select;

const OrderProcess = () => {
  const [orderStatus, setOrderStatus] = useState('全部');
  const [updateInterval, setUpdateInterval] = useState(1000);
  const [isUpdating, setIsUpdating] = useState(false);
  const updateTimerRef = useRef(null);
  const [displayData, setDisplayData] = useState([]);
  const [selectedOrders, setSelectedOrders] = useState([]);
  const [pendingCount, setPendingCount] = useState(0);
  const [processingCount, setProcessingCount] = useState(0);
  const [completedToday, setCompletedToday] = useState(0);
  const [efficiency, setEfficiency] = useState(95);

  const generateMockOrder = useCallback(idx => {
    const types = ['借阅', '归还', '预约', '续借'];
    const statuses = ['待处理', '处理中', '已完成', '已取消'];
    const books = [
      'JavaScript高级程序设计',
      'Python数据分析',
      '深入理解计算机系统',
      '算法导论',
      '设计模式',
      '代码整洁之道',
      'Vue.js实战',
      'React设计模式',
    ];
    const users = [
      '张三',
      '李四',
      '王五',
      '赵六',
      '钱七',
      '孙八',
      '周九',
      '吴十',
    ];

    return {
      key: `ORD${String(idx + 1).padStart(6, '0')}`,
      id: `ORD${String(idx + 1).padStart(6, '0')}`,
      bookName: books[Math.floor(Math.random() * books.length)],
      userName: users[Math.floor(Math.random() * users.length)],
      type: types[Math.floor(Math.random() * types.length)],
      status: statuses[Math.floor(Math.random() * statuses.length)],
      progress: Math.floor(Math.random() * 100),
      createTime: new Date(
        Date.now() - Math.floor(Math.random() * 86400000)
      ).toLocaleString(),
      updateTime: new Date().toLocaleString(),
    };
  }, []);

  const updateStats = useCallback(() => {
    setPendingCount(
      displayData.filter(order => order.status === '待处理').length
    );
    setProcessingCount(
      displayData.filter(order => order.status === '处理中').length
    );
    setCompletedToday(
      displayData.filter(order => order.status === '已完成').length
    );
    setEfficiency(Math.floor(Math.random() * 10 + 90));
  }, [displayData]);

  useEffect(() => {
    updateStats();
  }, [displayData, updateStats]);

  useEffect(() => {
    const start = performance.now();
    const initialOrders = Array.from({ length: 100 }, (_, idx) =>
      generateMockOrder(idx)
    );
    
    setDisplayData(initialOrders);
    const end = performance.now();
    message.success(`生成1000条订单耗时：${(end - start).toFixed(2)}ms`);
  }, [generateMockOrder]);

  useEffect(() => {
    return () => {
      if (updateTimerRef.current) {
        clearInterval(updateTimerRef.current);
      }
    };
  }, []);

  const getOrderType = useCallback(type => {
    const types = {
      借阅: 'blue',
      归还: 'green',
      预约: 'orange',
      续借: 'purple',
    };
    return types[type] || 'default';
  }, []);

  const getStatusType = useCallback(status => {
    const types = {
      待处理: 'text-yellow-500',
      处理中: 'text-blue-500',
      已完成: 'text-green-500',
      已取消: 'text-red-500',
    };
    return types[status] || 'text-gray-500';
  }, []);

  const getProgressStatus = useCallback(progress => {
    if (progress >= 100) return 'success';
    if (progress >= 80) return 'exception';
    return 'normal';
  }, []);

  const handleProcess = useCallback(order => {
    message.success(`开始处理订单：${order.id}`);

    setDisplayData(prevData =>
      prevData.map(item =>
        item.id === order.id
          ? { ...item, status: '处理中', progress: 50 }
          : item
      )
    );
  }, []);

  const handleCancel = useCallback(order => {
    Modal.confirm({
      title: '确认取消该订单吗？',
      icon: <ExclamationCircleOutlined />,
      content: `订单号: ${order.id}`,
      okText: '确定',
      cancelText: '取消',
      onOk() {
        message.success(`已取消订单：${order.id}`);

        setDisplayData(prevData =>
          prevData.map(item =>
            item.id === order.id
              ? { ...item, status: '已取消', progress: 0 }
              : item
          )
        );
      },
      onCancel() {},
    });
  }, []);

  const handleDetail = useCallback(order => {
    message.info(`查看订单详情：${order.id}`);
  }, []);

  const handleBatchProcess = useCallback(() => {
    if (selectedOrders.length === 0) {
      message.warning('请先选择要处理的订单');
      return;
    }
    message.success(`批量处理 ${selectedOrders.length} 个订单`);

    setDisplayData(prevData =>
      prevData.map(order =>
        selectedOrders.some(selected => selected.id === order.id)
          ? { ...order, status: '处理中', progress: 50 }
          : order
      )
    );
    setSelectedOrders([]);
  }, [selectedOrders]);

  const handleSelectionChange = useCallback((selectedRowKeys, selectedRows) => {
    setSelectedOrders(selectedRows);
  }, []);

  const startUpdate = useCallback(() => {
    setIsUpdating(true);
    updateTimerRef.current = setInterval(() => {
      const newOrders = Array.from({ length: 20 }, (_, idx) =>
        generateMockOrder(idx)
      );
      setDisplayData(newOrders);
    }, updateInterval);
  }, [updateInterval, generateMockOrder]);

  const stopUpdate = useCallback(() => {
    setIsUpdating(false);
    if (updateTimerRef.current) {
      clearInterval(updateTimerRef.current);
      updateTimerRef.current = null;
    }
  }, []);

  const toggleUpdate = useCallback(() => {
    if (isUpdating) {
      stopUpdate();
    } else {
      startUpdate();
    }
  }, [isUpdating, startUpdate, stopUpdate]);

  const handleIntervalChange = useCallback(
    value => {
      setUpdateInterval(value);
      if (isUpdating) {
        stopUpdate();
        startUpdate();
      }
    },
    [isUpdating, startUpdate, stopUpdate]
  );

  const generate2000Orders = useCallback(() => {
    const start = performance.now();
    const newOrders = Array.from({ length: 2000 }, (_, idx) =>
      generateMockOrder(idx)
    );
    setDisplayData(newOrders);

    setTimeout(() => {
      const end = performance.now();
      message.success(`生成2000条订单耗时：${(end - start).toFixed(2)}ms`);
    }, 0);
  }, [generateMockOrder]);

  const shuffleOrders = useCallback(() => {
    const start = performance.now();
    const arr = [...displayData];
    for (let i = arr.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [arr[i], arr[j]] = [arr[j], arr[i]];
    }
    setDisplayData(arr);
    setTimeout(() => {
      const end = performance.now();
      message.success(`打乱顺序耗时：${(end - start).toFixed(2)}ms`);
    }, 0);
  }, [displayData]);

  const insertRandomOrder = useCallback(() => {
    const start = performance.now();
    const idx = Math.floor(Math.random() * (displayData.length + 1));
    const newOrder = generateMockOrder(displayData.length);
    const newDisplayData = [...displayData];
    newDisplayData.splice(idx, 0, newOrder);
    setDisplayData(newDisplayData);
    setTimeout(() => {
      const end = performance.now();
      message.success(`插入订单耗时：${(end - start).toFixed(2)}ms`);
    }, 0);
  }, [displayData, generateMockOrder]);

  const deleteRandomOrder = useCallback(() => {
    if (displayData.length === 0) return;
    const start = performance.now();
    const idx = Math.floor(Math.random() * displayData.length);
    const newDisplayData = [...displayData];
    newDisplayData.splice(idx, 1);
    setDisplayData(newDisplayData);
    setTimeout(() => {
      const end = performance.now();
      message.success(`删除订单耗时：${(end - start).toFixed(2)}ms`);
    }, 0);
  }, [displayData]);

  const replaceAllOrders = useCallback(() => {
    const start = performance.now();
    const len = displayData.length;
    const newOrders = Array.from({ length: len }, (_, idx) =>
      generateMockOrder(idx)
    );
    setDisplayData(newOrders);
    setTimeout(() => {
      const end = performance.now();
      message.success(`替换所有订单耗时：${(end - start).toFixed(2)}ms`);
    }, 0);
  }, [displayData, generateMockOrder]);

  const columns = useMemo(
    () => [
      {
        title: '订单号',
        dataIndex: 'id',
        key: 'id',
        width: 90,
        align: 'center',
      },
      {
        title: '图书名称',
        dataIndex: 'bookName',
        key: 'bookName',
        width: 140,
        align: 'center',
        ellipsis: true,
      },
      {
        title: '用户',
        dataIndex: 'userName',
        key: 'userName',
        width: 70,
        align: 'center',
      },
      {
        title: '类型',
        dataIndex: 'type',
        key: 'type',
        width: 70,
        align: 'center',
        render: text => (
          <Tag
            color={getOrderType(text)}
            className='rounded-md px-1 py-0.5 text-xs'
          >
            {text}
          </Tag>
        ),
      },
      {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
        width: 70,
        align: 'center',
        render: text => (
          <span className={`font-medium ${getStatusType(text)}`}>{text}</span>
        ),
      },
      {
        title: '处理进度',
        dataIndex: 'progress',
        key: 'progress',
        width: 130,
        align: 'center',
        render: progress => (
          <Progress
            percent={progress}
            status={getProgressStatus(progress)}
            strokeWidth={12}
            className='m-0'
          />
        ),
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        key: 'createTime',
        width: 130,
        align: 'center',
      },
      {
        title: '操作',
        key: 'actions',
        width: 150,
        align: 'center',
        render: (_, record) => (
          <div className='flex justify-center space-x-1'>
            <Button
              size='small'
              type='primary'
              onClick={() => handleProcess(record)}
            >
              处理
            </Button>
            <Button
              size='small'
              type='primary'
              danger
              onClick={() => handleCancel(record)}
            >
              取消
            </Button>
            <Button size='small' onClick={() => handleDetail(record)}>
              详情
            </Button>
          </div>
        ),
      },
    ],
    [
      getOrderType,
      getStatusType,
      getProgressStatus,
      handleProcess,
      handleCancel,
      handleDetail,
    ]
  );

  const rowSelection = {
    selectedRowKeys: selectedOrders.map(order => order.key),
    onChange: handleSelectionChange,
  };

  return (
    <div className='p-6 bg-gray-50 min-h-screen font-sans'>
      <div className='page-header mb-6 block'>
        <div className='flex gap-4 items-center justify-center'>
          <h1 className='page-heading '>
            订单处理中心
          </h1>
          <KeyStrategyDisplay />
        </div>
        <div className='description mt-4 px-16'>
          <Alert
            message='模块说明'
            description='订单处理中心用于管理和处理图书借阅、归还、预约等订单。支持实时更新和批量处理功能。'
            type='info'
            showIcon
            closable={false}
            className='rounded-lg shadow-sm'
          />
        </div>
      </div>

      <div className='control-panel bg-white p-6 rounded-lg shadow-md mb-6'>
        <div className='flex justify-center'>
          <Form layout='inline' className='flex flex-wrap items-center gap-4'>
            <Form.Item label='订单状态' className='mb-0'>
              <Select
                value={orderStatus}
                onChange={setOrderStatus}
                placeholder='选择状态'
                className='min-w-[120px] rounded-md'
              >
                <Option value='全部'>全部</Option>
                <Option value='待处理'>待处理</Option>
                <Option value='处理中'>处理中</Option>
                <Option value='已完成'>已完成</Option>
                <Option value='已取消'>已取消</Option>
              </Select>
            </Form.Item>
            <Form.Item label='更新频率' className='mb-0'>
              <InputNumber
                min={100}
                max={5000}
                step={100}
                value={updateInterval}
                onChange={handleIntervalChange}
                className='rounded-md'
              />
            </Form.Item>
          </Form>
        </div>

        <div className='btn-group flex justify-center mt-8'>
          <Button
            type={isUpdating ? 'default' : 'primary'}
            onClick={toggleUpdate}
            className='mr-2 rounded-md shadow-sm'
          >
            {isUpdating ? '暂停自动刷新' : '开启自动刷新'}
          </Button>
          <Button
            type='primary'
            onClick={handleBatchProcess}
            className='mr-2 rounded-md shadow-sm bg-green-500 hover:bg-green-600 border-green-500 hover:border-green-600'
          >
            批量处理
          </Button>
          <Button
            type='primary'
            onClick={generate2000Orders}
            className='mr-2 rounded-md shadow-sm'
          >
            生成2000条
          </Button>
          <Button
            type='primary'
            onClick={insertRandomOrder}
            className='mr-2 rounded-md shadow-sm bg-green-500 hover:bg-green-600 border-green-500 hover:border-green-600'
          >
            插入订单
          </Button>
          <Button
            type='default'
            onClick={deleteRandomOrder}
            className='mr-2 rounded-md shadow-sm bg-red-500 hover:bg-red-600 border-red-500 hover:border-red-600 text-white'
          >
            删除订单
          </Button>
          <Button
            type='default'
            onClick={replaceAllOrders}
            className='mr-2 rounded-md shadow-sm bg-gray-500 hover:bg-gray-600 border-gray-500 hover:border-gray-600 text-white'
          >
            替换所有
          </Button>
          <Button
            type='default'
            onClick={shuffleOrders}
            className='rounded-md shadow-sm bg-yellow-500 hover:bg-yellow-600 border-yellow-500 hover:border-yellow-600 text-white'
          >
            打乱顺序
          </Button>
        </div>
      </div>

      <div className='performance-stats mb-6'>
        <Row gutter={[20, 20]}>
          <Col span={6}>
            <div className='bg-white p-4 rounded-lg shadow-md text-center p-8'>
              <div className='stat-title text-gray-500 text-sm mb-1'>
                待处理订单
              </div>
              <div className='stat-value text-3xl font-bold text-yellow-600'>
                {pendingCount}
              </div>
            </div>
          </Col>
          <Col span={6}>
            <div className='bg-white p-4 rounded-lg shadow-md text-center p-8'>
              <div className='stat-title text-gray-500 text-sm mb-1'>
                处理中订单
              </div>
              <div className='stat-value text-3xl font-bold text-blue-600'>
                {processingCount}
              </div>
            </div>
          </Col>
          <Col span={6}>
            <div className='bg-white p-4 rounded-lg shadow-md text-center p-8'>
              <div className='stat-title text-gray-500 text-sm mb-1'>
                今日完成
              </div>
              <div className='stat-value text-3xl font-bold text-green-600'>
                {completedToday}
              </div>
            </div>
          </Col>
          <Col span={6}>
            <div className='bg-white p-4 rounded-lg shadow-md text-center p-8'>
              <div className='stat-title text-gray-500 text-sm mb-1'>
                处理效率
              </div>
              <div className='stat-value text-3xl font-bold text-purple-600'>
                {efficiency}%
              </div>
            </div>
          </Col>
        </Row>
      </div>

      <div className='table-container bg-white rounded-lg shadow-md overflow-hidden'>
        <Table
          dataSource={displayData.filter(order =>
            orderStatus ? order.status === orderStatus : true
          )}
          columns={columns}
          rowSelection={rowSelection}
          pagination={false}
          scroll={{ y: 'calc(100vh - 450px)' }}
          bordered
          className='rounded-lg'
        />
      </div>
    </div>
  );
};

export default OrderProcess;

